<?php

namespace backend\modules\log\models;

use Yii;
use yii\base\Action;
use yii\base\Exception;

/**
 * This is the model class for table "adminlog".
 *
 * @property string $id
 * @property string $ip
 * @property string $username
 * @property string $controller
 * @property string $action
 * @property string $module
 * @property integer $created_at
 */
class Adminlog extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'adminlog';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ip', 'username', 'controller', 'action', 'module', 'created_at'], 'required'],
            [['created_at'], 'integer'],
            [['ip'], 'string', 'max' => 16],
            [['username'], 'string', 'max' => 60],
            [['controller', 'action', 'module'], 'string', 'max' => 200],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'ip' => Yii::t('app', '用户操作IP地址'),
            'username' => Yii::t('app', '账号名称'),
            'module' => Yii::t('app', '功能模块（哪一块功能）'),
            'controller' => Yii::t('app', '控制器（那个页面）'),
            'action' => Yii::t('app', '执行方法（具体操作了什么）'),
            'created_at' => Yii::t('app', '操作时间'),
        ];
    }

    /**
     * @inheritdoc
     * @return \backend\modules\log\models\query\AdminlogQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \backend\modules\log\models\query\AdminlogQuery(get_called_class());
    }

    /**
     * @param $moduleId
     * @param $controllerId
     * @param $actionId
     * @return bool
     * @throws Exception
     */
    public static function saveLog($moduleId,$controllerId,$actionId)
    {
        if(!Yii::$app->user->identity){
            return true;
        }
        $newAdminlog = new Adminlog();
        $newAdminlog->module = $moduleId;
        $newAdminlog->controller = $controllerId;
        $newAdminlog->action = $actionId;
        $newAdminlog->ip = $_SERVER['REMOTE_ADDR'] ;
        $newAdminlog->username = isset(Yii::$app->user->identity->username)?Yii::$app->user->identity->username:'';
        $newAdminlog->created_at = time();
        if(!$newAdminlog->save())
        {
            throw  new Exception('日志出错了');
        }
        return true;
    }
}
